/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import ReactEcharts from 'echarts-for-react';
import { Button, Input, Menu, Message, Icon } from '@alifd/next';
import styles from './index.module.scss';
import classnames from 'classnames';
import 'echarts/lib/chart/graph'; // 折线图是line,饼图改为pie,柱形图改为bar
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/markPoint';
import 'echarts/dist/extension/bmap.min.js';
import 'echarts/map/js/province/fujian.js';

const { Item } = Menu;

let searchResultList = [];
export default class mMap extends Component {
    constructor(props) {
        super(props);

        this.state = {
            mapInited: false,
            isFull: false,

            searchValue: '',
        };

        this.node = [];
        this.line = [];
        this.zoom = 14;
        this.currentClickPoint = {};
        this.echartsInstance = null;
        this.echarts = null;
        this.bmap = null;
        this.nowEvent = null;

        this.init = this.init.bind(this);
        this.doSearch = this.doSearch.bind(this);
    }

    componentDidMount() {
        this.init();
    }
    componentWillReceiveProps(nextProps) {
    // console.log('执行了componentWillReceiveProps');
        if (this.state.mapInited) {
            this.drarPoint(nextProps.list);
        }
    }
  init = async () => {

  }
  componentWillUnmount() {
      this.setState({
          mapInited: false,
      });
  }

  initBmap = (echarts) => {
      this.bmap = echarts
          .getEchartsInstance()
          .getModel()
          .getComponent('bmap')
          .getBMap();

      // eslint-disable-next-line no-undef
      const scaleCtrl = new BMap.ScaleControl(); // 添加比例尺控件
      this.bmap.addControl(scaleCtrl);
      this.bmap.setMaxZoom(22);
      // eslint-disable-next-line no-undef
      this.bmap.addControl(new BMap.MapTypeControl({
          mapTypes: [
              // eslint-disable-next-line no-undef
              BMAP_HYBRID_MAP, // 卫星地图
              // eslint-disable-next-line no-undef
              BMAP_NORMAL_MAP, // 正常地图
          ],
      }));
      // eslint-disable-next-line no-undef
      this.bmap.setMapType(BMAP_HYBRID_MAP);
      if (this.props.isSelect) {
          this.bmap.addEventListener(
              'rightclick',
              this.canvasRightClickCall.bind(this),
          );
      }


      this.bmap.addEventListener('click', this.canvasClick.bind(this));
      // this.bmap.setMapType('BMAP_HYBRID_MAP');
  };
  canvasClick = () => {
      this.closeAllMenu();
  };
  canvasRightClickCall = (eventInfo) => {
      this.currentClickPoint = eventInfo.point;// 当前点
      this.zoom = this.bmap?.getZoom();// 缩放比例

      this.closeAllMenu();

      const menu = document.getElementById('canvasMenu');
      menu.style.display = 'block';

      const scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop;
      menu.style.left = `${eventInfo.domEvent.clientX}px`;
      menu.style.top = `${eventInfo.domEvent.clientY + scrollTop}px`;
  };

  getOption = () => {
      let defaultCenter = this.props.defaultCenter || [118.546968, 24.844884];
      const defaultZoom = this.props.defaultZoom || 14;
      if (
          this.echartsInstance != null &&
      this.echartsInstance.getOption() != null
      ) {
          defaultCenter = [this.bmap.getCenter().lng, this.bmap.getCenter().lat];
      }

      const option = {
          title: {
              text: '位置',
          },

          tooltip: {
              formatter: (param) => {
                  const originData = param.data.originData;
                  // const type = originData.team === 'red' ? '红队' : originData.team === 'blue' ? '蓝队' : originData.team === 'yellow' ? '人质' : '劫匪';
                  return `${originData.id}号:<br/>生命值${originData.hp}<br/>主武器弹药${originData.ammo1}<br/>副武器弹药${originData.ammo2}`;
              },
          },
          bmap: {
              center: defaultCenter,
              // 百度地图缩放
              zoom: this.bmap?.getZoom() || defaultZoom,
              // 是否开启拖拽缩放，可以只设置 'scale' 或者 'move'
              roam: true,
          },
          series: [
              {
                  type: 'graph',
                  coordinateSystem: 'bmap',
                  geoIndex: 0,
                  animation: false,
                  nodes: this.node,
                  emphasis: {
                      focus: 'series',
                      scale: true,
                  },
                  symbolSize: 20,
                  edges: [],
                  label: {
                      show: true,
                      color: '#fff',
                      fontWeight: 'bold',
                  },
                  roam: true,
                  focusNodeAdjacency: true,
                  zLevel: 1,
                  lineStyle: {
                      color: 'rgb(0,0,0)',
                  },
              },
          ],
      };
      return option;
  };
  setEChart = (echarts) => {
      if (echarts != null) {
          this.echarts = echarts;
          this.echartsInstance = echarts.getEchartsInstance();
          this.initBmap(this.echarts);
          this.drarPoint([]);
      }
  };

  drarPoint = (list) => {
      this.node = [];
      const option = this.echartsInstance.getOption();
      // const list = this.state.list;
      // const arr = [
      //   {
      //     lat: 24.866455,
      //     lng: 118.69206,
      //     id: 10,
      //     name: '小明',
      //     team: 'red',
      //   },
      //   {
      //     lat: 25.31312,
      //     lng: 117.252047,
      //     id: '11',
      //     name: '小王',
      //     team: 'blue',
      //   },
      //   {
      //     lat: 25.32312,
      //     lng: 117.650047,
      //     id: '13',
      //     name: '大王',
      //     team: 'orange',
      //   },
      // ];

      // arr.forEach((data) => {
      //   this.node.push(this.setStyle(data));
      // });
      list = list.filter(i => i.lng && i.lat);// 过滤未设置的点
      list.forEach((data) => {
          this.node.push(this.setStyle(data));
      });

      option.series[0].nodes = this.node;


      this.echartsInstance.setOption(option);
  }
  setStyle = (data) => {
      const newNode = {};
      newNode.originData = data;
      newNode.name = data.id;
      newNode.id = data.id;
      newNode.itemStyle = {};
      newNode.label = {
          show: true,
      };
      // newNode.symbol = 'rect';
      // newNode.itemStyle = {
      //   color: '#f5222d',
      // };
      newNode.symbol = 'circle';
      if (data.hp === 0) { // 阵亡
          newNode.itemStyle.color = '#000';
      } else {
          switch (data.team) {
          case 'red':
              newNode.itemStyle.color = 'red';
              break;
          case 'orange':
              newNode.itemStyle.color = 'orange';
              break;

          case 'yellow':
              newNode.itemStyle.color = 'brown';// 劫匪改成棕色
              break;
          case 'blue':
              newNode.itemStyle.color = 'blue';
              break;
          default:
              newNode.itemStyle.color = 'red';
              break;
          }
      }


      newNode.value = [data.lng, data.lat];

      return newNode;
  }
  closeAllMenu = () => {
      document.getElementById('canvasMenu').style.display = 'none';
  };
  canvasMenuClickCall = (value) => {
      if (value == 'addCenter') {
          this.addMark();
      }
  };
  outAddMark = (point) => {
      if (point.lng && point.lat) { // 经纬度都不为0才显示出来
          // eslint-disable-next-line no-undef
          this.marker1 = new BMap.Marker(new BMap.Point(point.lng, point.lat));

          // 在地图上添加点标记
          this.bmap.addOverlay(this.marker1);
      }
  }
  addMark = () => {
      const point = this.currentClickPoint;
      if (this.marker1) {
          this.bmap.removeOverlay(this.marker1);
      }
      // 创建点标记
      // eslint-disable-next-line no-undef
      this.marker1 = new BMap.Marker(new BMap.Point(point.lng, point.lat));

      // 在地图上添加点标记
      this.bmap.addOverlay(this.marker1);
      this.closeAllMenu();
      if (typeof this.props.selectCb === 'function') {
          this.props.selectCb({ point: this.currentClickPoint, zoom: this.zoom });
      }
  }
  CanvasMenu = () => (
      <div
          id="canvasMenu"
          style={{
              width: '130px',
              background: '#CCC',
              position: 'absolute',
              display: 'none',
          }}
      >
          <Menu onItemClick={this.canvasMenuClickCall}>
              <Item key="addCenter">添加中心点</Item>

          </Menu>
      </div>
  );
  fullScreen = () => {
      this.setState({
          isFull: !this.state.isFull,
      });
  }

  doSearch = () => {
      // 百度地图API功能
      // var map = new BMapGL.Map("l-map");
      // this.bmap.centerAndZoom(new BMap.Point(this.bmap.getCenter().lng, this.bmap.getCenter().lat), 11);


      if (!this.state.searchValue) {
          Message.error('请输入搜索内容');
          return;
      }
      const _this = this;
      const options = {
          onSearchComplete(results) {
              // 判断状态是否正确
              // eslint-disable-next-line no-undef
              if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                  const s = [];
                  for (let i = 0; i < results.getCurrentNumPois(); i++) {
                      s.push({

                          title: results.getPoi(i).title,
                          address: results.getPoi(i).address,
                          lng: results.getPoi(i).point.lng,
                          lat: results.getPoi(i).point.lat,

                      });
                  }

                  searchResultList = s;
                  if (searchResultList.length === 0) {
                      Message.error('没有搜索内容,请换个关键词搜索');
                  }
                  _this.setState({
                      noUse: Math.random(),
                  });
                  // document.getElementById('r-result').innerHTML = s.join('<br/>');
              } else {
                  Message.error('搜索错误,请换个关键词搜索!');
              }
          },
      };
      // eslint-disable-next-line no-undef
      let local = new BMap.LocalSearch(this.bmap, options);
      local.search(this.state.searchValue);
  }

  handleItemClick=(item) => {
      this.currentClickPoint = { lng: item.lng, lat: item.lat };

      searchResultList = [];
      this.setState({
          searchValue: '',
      });
      // eslint-disable-next-line no-undef
      this.bmap.centerAndZoom(new BMap.Point(item.lng, item.lat), this.bmap?.getZoom());
      this.addMark();
  }
  render() {
      return (


          <div id="echartsCanvas" className={classnames(this.state.isFull ? styles.wrap2 : styles.wrap1, !this.props.unRelative ? styles.unRelative : null)} >
              {
                  this.props.isShowSearch ?
                      <div className={styles.serachWrap} >
                          <div className={styles.SearchBar} >
                              <div>
                                  <Input
                                      placeholder="搜索地名"
                                      value={this.state.searchValue}
                                      onChange={(e) => {
                                          this.setState({
                                              searchValue: e,
                                          });
                                      }}
                                  />
                                  <Button onClick={this.doSearch} type="primary" >搜索</Button>
                              </div>


                              <div className={styles.results} >
                                  {
                                      searchResultList.map(item => (<div className={styles.result} onClick={() => { this.handleItemClick(item); }}>


                                          <Icon style={{ color: '#999' }} type="favorites-filling" />
                                          <div className="flex box ml column" >
                                              <div className={styles.name} >{item.title}</div>
                                              <div className={styles.label} >{item.address}</div>
                                          </div>

                                      </div>))
                                  }
                              </div>

                          </div>

                      </div>
                      : null
              }
              <ReactEcharts
                  className={classnames(this.state.isFull ? styles.wrap2 : styles.wrap1)}
                  style={{ width: '100%', height: '100%' }}
                  ref={this.setEChart}
                  option={this.getOption()}
                  theme="Imooc"
              />
              <this.CanvasMenu />


              {
                  this.props.showFullButton ? <Button onClick={this.fullScreen} type="primary" className={styles.button} >
            切换
                  </Button> : null
              }


          </div>

      );
  }
}
